<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js,js 机制,浏览器机制," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="很多人都知道要减少浏览器的重排和重绘，但对其中的具体原理以及如何具体操作并不是很了解，当突然提起这个话题的时候，还是会一脸懵逼。希望大家可以耐着性子阅读本文，仔细琢磨，彻底掌握这个知识点！">
<meta name="keywords" content="js,js 机制,浏览器机制">
<meta property="og:type" content="article">
<meta property="og:title" content="轻松掌握浏览器重绘重排原理">
<meta property="og:url" content="http://yoursite.com/2018/12/18/轻松掌握浏览器重绘重排原理/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="很多人都知道要减少浏览器的重排和重绘，但对其中的具体原理以及如何具体操作并不是很了解，当突然提起这个话题的时候，还是会一脸懵逼。希望大家可以耐着性子阅读本文，仔细琢磨，彻底掌握这个知识点！">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1fya3fh2jm3j30ku0dwtb2.jpg?raw=true">
<meta property="og:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/167b642d014afaf1?w=651&h=314&f=png&s=123051?raw=true">
<meta property="og:updated_time" content="2019-07-20T06:55:39.065Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="轻松掌握浏览器重绘重排原理">
<meta name="twitter:description" content="很多人都知道要减少浏览器的重排和重绘，但对其中的具体原理以及如何具体操作并不是很了解，当突然提起这个话题的时候，还是会一脸懵逼。希望大家可以耐着性子阅读本文，仔细琢磨，彻底掌握这个知识点！">
<meta name="twitter:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1fya3fh2jm3j30ku0dwtb2.jpg?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/12/18/轻松掌握浏览器重绘重排原理/"/>





  <title>轻松掌握浏览器重绘重排原理 | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/12/18/轻松掌握浏览器重绘重排原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">轻松掌握浏览器重绘重排原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-18T10:42:31+08:00">
                2018-12-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/浏览器机制/" itemprop="url" rel="index">
                    <span itemprop="name">浏览器机制</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/12/18/轻松掌握浏览器重绘重排原理/" class="leancloud_visitors" data-flag-title="轻松掌握浏览器重绘重排原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,676 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1fya3fh2jm3j30ku0dwtb2.jpg?raw=true" alt=""></p>
<p>很多人都知道要减少浏览器的重排和重绘，但对其中的具体原理以及如何具体操作并不是很了解，当突然提起这个话题的时候，还是会一脸懵逼。希望大家可以耐着性子阅读本文，仔细琢磨，彻底掌握这个知识点！</p>
<a id="more"></a>
<blockquote>
<p><a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="http://obkoro1.com/web_accumulate/accumulate/" target="_blank" rel="noopener">前端积累文档</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a>、<a href="https://github.com/OBKoro1" target="_blank" rel="noopener">GitHub</a></p>
</blockquote>
<h3 id="网页生成过程："><a href="#网页生成过程：" class="headerlink" title="网页生成过程："></a>网页生成过程：</h3><ol>
<li>HTML被HTML解析器解析成DOM 树</li>
<li>css则被css解析器解析成CSSOM 树</li>
<li>结合DOM树和CSSOM树，生成一棵渲染树(Render Tree)</li>
<li>生成布局（flow），即将所有渲染树的所有节点进行平面合成</li>
<li>将布局绘制（paint）在屏幕上</li>
</ol>
<p>第四步和第五步是最耗时的部分，这两步合起来，就是我们通常所说的<strong>渲染</strong>。</p>
<p>网上找了一张图片，我加了注释会更直观一些：</p>
<p><img src="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/167b642d014afaf1?w=651&amp;h=314&amp;f=png&amp;s=123051?raw=true" alt=""></p>
<hr>
<h2 id="渲染："><a href="#渲染：" class="headerlink" title="渲染："></a>渲染：</h2><p><strong>网页生成的时候，至少会渲染一次</strong>。</p>
<p><strong>在用户访问的过程中，还会不断重新渲染</strong></p>
<p>重新渲染需要重复之前的第四步(重新生成布局)+第五步(重新绘制)或者只有第五个步(重新绘制)。</p>
<h3 id="重排比重绘大："><a href="#重排比重绘大：" class="headerlink" title="重排比重绘大："></a>重排比重绘大：</h3><p>大，在这个语境里的意思是：谁能影响谁？</p>
<ul>
<li>重绘：某些元素的外观被改变，例如：元素的填充颜色</li>
<li>重排：重新生成布局，重新排列元素。</li>
</ul>
<p>就如上面的概念一样，<strong>单单改变元素的外观，肯定不会引起网页重新生成布局，但当浏览器完成重排之后，将会重新绘制受到此次重排影响的部分</strong>。</p>
<pre><code>比如改变元素高度，这个元素乃至周边dom都需要重新绘制。
</code></pre><p>也就是说：<strong>“重绘”不一定会出现”重排”，”重排”必然会出现”重绘”</strong></p>
<h2 id="重排-reflow-："><a href="#重排-reflow-：" class="headerlink" title="重排(reflow)："></a>重排(reflow)：</h2><h3 id="概念："><a href="#概念：" class="headerlink" title="概念："></a>概念：</h3><p>当DOM的变化影响了元素的几何信息(DOM对象的位置和尺寸大小)，浏览器需要重新计算元素的几何属性，将其安放在界面中的正确位置，这个过程叫做重排。</p>
<p>重排也叫回流,重排的过程以下面这种理解方式更清晰一些：</p>
<blockquote>
<p>回流就好比向河里(文档流)扔了一块石头(dom变化)，激起涟漪，然后引起周边水流受到波及，所以叫做回流</p>
</blockquote>
<h3 id="常见引起重排属性和方法"><a href="#常见引起重排属性和方法" class="headerlink" title="常见引起重排属性和方法"></a>常见引起重排属性和方法</h3><p><strong>任何会改变元素几何信息(元素的位置和尺寸大小)的操作，都会触发重排</strong>，下面列一些栗子：</p>
<ol>
<li>添加或者删除可见的DOM元素；</li>
<li>元素尺寸改变——边距、填充、边框、宽度和高度</li>
<li>内容变化，比如用户在input框中输入文字</li>
<li>浏览器窗口尺寸改变——resize事件发生时</li>
<li>计算 offsetWidth 和 offsetHeight 属性</li>
<li>设置 style 属性的值</li>
</ol>
<table>
<thead>
<tr>
<th style="text-align:left">常见引起重排属性和方法</th>
<th style="text-align:left"></th>
<th style="text-align:left"></th>
<th style="text-align:left"></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">width</td>
<td style="text-align:left">height</td>
<td style="text-align:left">margin</td>
<td style="text-align:left">padding </td>
</tr>
<tr>
<td style="text-align:left">display</td>
<td style="text-align:left">border</td>
<td style="text-align:left">position</td>
<td style="text-align:left">overflow</td>
</tr>
<tr>
<td style="text-align:left">clientWidth</td>
<td style="text-align:left">clientHeight</td>
<td style="text-align:left">clientTop</td>
<td style="text-align:left">clientLeft</td>
</tr>
<tr>
<td style="text-align:left">offsetWudth</td>
<td style="text-align:left">offsetHeight</td>
<td style="text-align:left">offsetTop</td>
<td style="text-align:left">offsetLeft</td>
</tr>
<tr>
<td style="text-align:left">scrollWidth</td>
<td style="text-align:left">scrollHeight</td>
<td style="text-align:left">scrollTop</td>
<td style="text-align:left">scrollLeft</td>
</tr>
<tr>
<td style="text-align:left">scrollIntoView()</td>
<td style="text-align:left">scrollTo()</td>
<td style="text-align:left">getComputedStyle()    </td>
</tr>
<tr>
<td style="text-align:left">getBoundingClientRect()</td>
<td style="text-align:left">scrollIntoViewIfNeeded()    </td>
</tr>
</tbody>
</table>
<h3 id="重排影响的范围："><a href="#重排影响的范围：" class="headerlink" title="重排影响的范围："></a>重排影响的范围：</h3><p>由于浏览器渲染界面是基于流失布局模型的，所以触发重排时会对周围DOM重新排列，影响的范围有两种：</p>
<ul>
<li>全局范围：从根节点<code>html</code>开始对整个渲染树进行重新布局。</li>
<li>局部范围：对渲染树的某部分或某一个渲染对象进行重新布局</li>
</ul>
<p><strong>全局范围重排</strong>：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"hello"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h4</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">h4</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">strong</span>&gt;</span>Name:<span class="tag">&lt;/<span class="name">strong</span>&gt;</span>BDing<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h5</span>&gt;</span>male<span class="tag">&lt;/<span class="name">h5</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ol</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span>&gt;</span>coding<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span>&gt;</span>loving<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ol</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>当p节点上发生reflow时，hello和body也会重新渲染，甚至h5和ol都会收到影响。</p>
<p><strong>局部范围重排：</strong></p>
<p>用局部布局来解释这种现象：把一个dom的宽高之类的几何信息定死，然后在dom内部触发重排，就只会重新渲染该dom内部的元素，而不会影响到外界。</p>
<h3 id="尽可能的减少重排的次数、重排范围："><a href="#尽可能的减少重排的次数、重排范围：" class="headerlink" title="尽可能的减少重排的次数、重排范围："></a>尽可能的减少重排的次数、重排范围：</h3><p>重排需要更新渲染树,性能花销非常大:</p>
<p>它们的代价是高昂的，会破坏用户体验，并且让UI展示非常迟缓，我们需要尽可能的减少触发重排的次数。</p>
<p>重排的性能花销跟渲染树有多少节点需要重新构建有关系：</p>
<p>所以我们应该尽量以局部布局的形式组织<code>html</code>结构，尽可能小的影响重排的范围。</p>
<p>而不是像全局范围的示例代码一样一溜的堆砌标签，随便一个元素触发重排都会导致全局范围的重排。</p>
<h2 id="重绘-Repaints"><a href="#重绘-Repaints" class="headerlink" title="重绘(Repaints):"></a>重绘(Repaints):</h2><p><strong>概念</strong>：</p>
<p>当一个元素的外观发生改变，但没有改变布局,重新把元素外观绘制出来的过程，叫做重绘。</p>
<p><strong>常见的引起重绘的属性</strong>:</p>
<table>
<thead>
<tr>
<th style="text-align:center"></th>
<th style="text-align:center"></th>
<th style="text-align:center"></th>
<th style="text-align:center"></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"> color</td>
<td style="text-align:center">border-style</td>
<td style="text-align:center">visibility</td>
<td style="text-align:center">background </td>
</tr>
<tr>
<td style="text-align:center"> text-decoration</td>
<td style="text-align:center">background-image</td>
<td style="text-align:center">background-position</td>
<td style="text-align:center">background-repeat</td>
<td></td>
</tr>
<tr>
<td style="text-align:center"> outline-color</td>
<td style="text-align:center">outline</td>
<td style="text-align:center">outline-style</td>
<td style="text-align:center">border-radius </td>
</tr>
<tr>
<td style="text-align:center"> outline-width</td>
<td style="text-align:center">box-shadow</td>
<td style="text-align:center">background-size</td>
</tr>
</tbody>
</table>
<hr>
<h2 id="浏览器的渲染队列："><a href="#浏览器的渲染队列：" class="headerlink" title="浏览器的渲染队列："></a>浏览器的渲染队列：</h2><p>思考以下代码将会触发几次渲染？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">div.style.left = <span class="string">'10px'</span>;</span><br><span class="line">div.style.top = <span class="string">'10px'</span>;</span><br><span class="line">div.style.width = <span class="string">'20px'</span>;</span><br><span class="line">div.style.height = <span class="string">'20px'</span>;</span><br></pre></td></tr></table></figure>
<p>根据我们上文的定义，这段代码理论上会触发4次重排+重绘，因为每一次都改变了元素的几何属性，实际上最后只触发了一次重排，这都得益于浏览器的<strong>渲染队列机制</strong>：</p>
<p>当我们修改了元素的几何属性，导致浏览器触发重排或重绘时。它会把该操作放进渲染队列，等到队列中的操作到了<strong>一定的数量或者到了一定的时间间隔</strong>时，浏览器就会批量执行这些操作。</p>
<h3 id="强制刷新队列"><a href="#强制刷新队列" class="headerlink" title="强制刷新队列:"></a>强制刷新队列:</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">div.style.left = <span class="string">'10px'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetLeft);</span><br><span class="line">div.style.top = <span class="string">'10px'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetTop);</span><br><span class="line">div.style.width = <span class="string">'20px'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetWidth);</span><br><span class="line">div.style.height = <span class="string">'20px'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetHeight);</span><br></pre></td></tr></table></figure>
<p>这段代码会触发4次重排+重绘，因为在<code>console</code>中你请求的这几个样式信息，无论何时浏览器都会立即执行渲染队列的任务，即使该值与你操作中修改的值没关联。</p>
<p><strong>因为队列中，可能会有影响到这些值的操作，为了给我们最精确的值，浏览器会立即重排+重绘</strong>。</p>
<p><strong>强制刷新队列的style样式请求</strong>：</p>
<ol>
<li>offsetTop, offsetLeft, offsetWidth, offsetHeight</li>
<li>scrollTop, scrollLeft, scrollWidth, scrollHeight</li>
<li>clientTop, clientLeft, clientWidth, clientHeight</li>
<li>getComputedStyle(), 或者 IE的 currentStyle</li>
</ol>
<p><strong>我们在开发中，应该谨慎的使用这些style请求，注意上下文关系,避免一行代码一个重排，这对性能是个巨大的消耗</strong></p>
<h2 id="重排优化建议"><a href="#重排优化建议" class="headerlink" title="重排优化建议"></a>重排优化建议</h2><p>就像上文提到的我们要尽可能的减少重排次数、重排范围，这样说很泛，下面是一些行之有效的建议，大家可以参考一下。</p>
<h3 id="1-分离读写操作"><a href="#1-分离读写操作" class="headerlink" title="1. 分离读写操作"></a>1. 分离读写操作</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">div.style.left = <span class="string">'10px'</span>;</span><br><span class="line">div.style.top = <span class="string">'10px'</span>;</span><br><span class="line">div.style.width = <span class="string">'20px'</span>;</span><br><span class="line">div.style.height = <span class="string">'20px'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetLeft);</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetTop);</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetWidth);</span><br><span class="line"><span class="built_in">console</span>.log(div.offsetHeight);</span><br></pre></td></tr></table></figure>
<p>还是上面触发4次重排+重绘的代码，这次只触发了一次重排：</p>
<p>在第一个<code>console</code>的时候，浏览器把之前上面四个写操作的渲染队列都给清空了。剩下的console，因为渲染队列本来就是空的，所以并没有触发重排，仅仅拿值而已。</p>
<h3 id="2-样式集中改变"><a href="#2-样式集中改变" class="headerlink" title="2. 样式集中改变"></a>2. 样式集中改变</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">div.style.left = <span class="string">'10px'</span>;</span><br><span class="line">div.style.top = <span class="string">'10px'</span>;</span><br><span class="line">div.style.width = <span class="string">'20px'</span>;</span><br><span class="line">div.style.height = <span class="string">'20px'</span>;</span><br></pre></td></tr></table></figure>
<p>虽然现在大部分浏览器有渲染队列优化，不排除有些浏览器以及老版本的浏览器效率仍然低下：</p>
<p>建议通过改变class或者csstext属性集中改变样式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// bad</span></span><br><span class="line"><span class="keyword">var</span> left = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">var</span> top = <span class="number">10</span>;</span><br><span class="line">el.style.left = left + <span class="string">"px"</span>;</span><br><span class="line">el.style.top  = top  + <span class="string">"px"</span>;</span><br><span class="line"><span class="comment">// good </span></span><br><span class="line">el.className += <span class="string">" theclassname"</span>;</span><br><span class="line"><span class="comment">// good</span></span><br><span class="line">el.style.cssText += <span class="string">"; left: "</span> + left + <span class="string">"px; top: "</span> + top + <span class="string">"px;"</span>;</span><br></pre></td></tr></table></figure>
<h3 id="3-缓存布局信息"><a href="#3-缓存布局信息" class="headerlink" title="3. 缓存布局信息"></a>3. 缓存布局信息</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// bad 强制刷新 触发两次重排</span></span><br><span class="line">div.style.left = div.offsetLeft + <span class="number">1</span> + <span class="string">'px'</span>;</span><br><span class="line">div.style.top = div.offsetTop + <span class="number">1</span> + <span class="string">'px'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// good 缓存布局信息 相当于读写分离</span></span><br><span class="line"><span class="keyword">var</span> curLeft = div.offsetLeft;</span><br><span class="line"><span class="keyword">var</span> curTop = div.offsetTop;</span><br><span class="line">div.style.left = curLeft + <span class="number">1</span> + <span class="string">'px'</span>;</span><br><span class="line">div.style.top = curTop + <span class="number">1</span> + <span class="string">'px'</span>;</span><br></pre></td></tr></table></figure>
<h3 id="4-离线改变dom"><a href="#4-离线改变dom" class="headerlink" title="4. 离线改变dom"></a>4. 离线改变dom</h3><ul>
<li><p>隐藏要操作的dom</p>
<p>  在要操作dom之前，通过display隐藏dom，当操作完成之后，才将元素的display属性为可见，因为不可见的元素不会触发重排和重绘。</p>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dom.display = <span class="string">'none'</span></span><br><span class="line"><span class="comment">// 修改dom样式</span></span><br><span class="line">dom.display = <span class="string">'block'</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p>通过使用<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/DocumentFragment" target="_blank" rel="noopener">DocumentFragment</a>创建一个<code>dom</code>碎片,在它上面批量操作dom，操作完成之后，再添加到文档中，这样只会触发一次重排。</p>
</li>
<li><p>复制节点，在副本上工作，然后替换它！</p>
</li>
</ul>
<h3 id="5-position属性为absolute或fixed"><a href="#5-position属性为absolute或fixed" class="headerlink" title="5. position属性为absolute或fixed"></a>5. position属性为absolute或fixed</h3><p>position属性为absolute或fixed的元素，重排开销比较小，不用考虑它对其他元素的影响</p>
<h3 id="6-优化动画"><a href="#6-优化动画" class="headerlink" title="6. 优化动画"></a>6. 优化动画</h3><ul>
<li><p>可以把动画效果应用到position属性为absolute或fixed的元素上，这样对其他元素影响较小</p>
<p>  动画效果还应牺牲一些平滑，来换取速度，这中间的度自己衡量：</p>
<p>  比如实现一个动画，以1个像素为单位移动这样最平滑，但是reflow就会过于频繁，大量消耗CPU资源，如果以3个像素为单位移动则会好很多。</p>
</li>
<li><p>启用GPPU加速</p>
<p>  此部分来自<a href="http://caibaojian.com/css-reflow-repaint.html" target="_blank" rel="noopener">优化CSS重排重绘与浏览器性能</a></p>
<p>  <strong>GPU(图像加速器)：</strong></p>
<p>  GPU 硬件加速是指应用 GPU 的图形性能对浏览器中的一些图形操作交给 GPU 来完成，因为 GPU 是专门为处理图形而设计，所以它在速度和能耗上更有效率。</p>
<p>  GPU 加速通常包括以下几个部分：Canvas2D，布局合成, CSS3转换（transitions），CSS3 3D变换（transforms），WebGL和视频(video)。</p>
</li>
</ul>
<pre><code><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 根据上面的结论</span></span><br><span class="line"><span class="comment"> * 将 2d transform 换成 3d</span></span><br><span class="line"><span class="comment"> * 就可以强制开启 GPU 加速</span></span><br><span class="line"><span class="comment"> * 提高动画性能</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">div &#123;</span><br><span class="line">  transform: translate3d(<span class="number">10</span>px, <span class="number">10</span>px, <span class="number">0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</code></pre><hr>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>重排也是导致DOM脚本执行效率低的关键因素之一，重排与重绘作为大厂经常出现的面试题，并且涉及的性能优化，这是前端必须掌握的基本概念/技能之一(敲黑板!)。</p>
<p>重排会不断触发这是不可避免的，但我们在开发时，应尽量按照文中的建议来组织代码，这种优化，需要平时有意识的去做，一点一滴的去做，希望大家重视一下。</p>
<h3 id="鼓励我一下："><a href="#鼓励我一下：" class="headerlink" title="鼓励我一下："></a>鼓励我一下：</h3><p>觉得还不错的话，给我的项目点个<a href="https://github.com/OBKoro1/Brush_algorithm" target="_blank" rel="noopener">star</a>吧</p>
<p>游泳、健身了解一下：<a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="https://github.com/OBKoro1/Brush_algorithm" target="_blank" rel="noopener">前端算法</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a></p>
<p> 以上2018.12.17</p>
<p> 参考资料：</p>
<p><a href="http://www.ruanyifeng.com/blog/2015/09/web-page-performance-in-depth.html" target="_blank" rel="noopener">网页性能管理详解</a></p>
<p><a href="http://caibaojian.com/css-reflow-repaint.html" target="_blank" rel="noopener">优化CSS重排重绘与浏览器性能</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          
            <a href="/tags/js-机制/" rel="tag"><i class="fa fa-tag"></i> js 机制</a>
          
            <a href="/tags/浏览器机制/" rel="tag"><i class="fa fa-tag"></i> 浏览器机制</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/02/网页全屏模式轻松掌握-局部元素全屏展示/" rel="next" title="网页全屏模式轻松掌握[局部元素全屏展示]">
                <i class="fa fa-chevron-left"></i> 网页全屏模式轻松掌握[局部元素全屏展示]
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/01/var和let-const的区别/" rel="prev" title="var和let/const的区别">
                var和let/const的区别 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#网页生成过程："><span class="nav-number">1.</span> <span class="nav-text">网页生成过程：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#渲染："><span class="nav-number"></span> <span class="nav-text">渲染：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#重排比重绘大："><span class="nav-number">1.</span> <span class="nav-text">重排比重绘大：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重排-reflow-："><span class="nav-number"></span> <span class="nav-text">重排(reflow)：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#概念："><span class="nav-number">1.</span> <span class="nav-text">概念：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常见引起重排属性和方法"><span class="nav-number">2.</span> <span class="nav-text">常见引起重排属性和方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#重排影响的范围："><span class="nav-number">3.</span> <span class="nav-text">重排影响的范围：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#尽可能的减少重排的次数、重排范围："><span class="nav-number">4.</span> <span class="nav-text">尽可能的减少重排的次数、重排范围：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重绘-Repaints"><span class="nav-number"></span> <span class="nav-text">重绘(Repaints):</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#浏览器的渲染队列："><span class="nav-number"></span> <span class="nav-text">浏览器的渲染队列：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#强制刷新队列"><span class="nav-number">1.</span> <span class="nav-text">强制刷新队列:</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重排优化建议"><span class="nav-number"></span> <span class="nav-text">重排优化建议</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-分离读写操作"><span class="nav-number">1.</span> <span class="nav-text">1. 分离读写操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-样式集中改变"><span class="nav-number">2.</span> <span class="nav-text">2. 样式集中改变</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-缓存布局信息"><span class="nav-number">3.</span> <span class="nav-text">3. 缓存布局信息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-离线改变dom"><span class="nav-number">4.</span> <span class="nav-text">4. 离线改变dom</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-position属性为absolute或fixed"><span class="nav-number">5.</span> <span class="nav-text">5. position属性为absolute或fixed</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-优化动画"><span class="nav-number">6.</span> <span class="nav-text">6. 优化动画</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number"></span> <span class="nav-text">结语</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#鼓励我一下："><span class="nav-number">1.</span> <span class="nav-text">鼓励我一下：</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

